import {
	Inject
} from 'plugins'
import config from 'config';

@Inject('$scope', '$state', 'ui.dialog', 'ui.http', 'ui.api')
export class MetaRuleList {
	constructor($scope, $state, dialog, http, api) {
		var q = $scope.q = {};

		var loadData = $scope.loadData = function(params) {
			api.gridLoad({
				name: 'meta_rules',
				params: params,
				scope: $scope
			});
		};

		var query = $scope.query = function(resetPage) {
			if (resetPage === false || $scope.gridOptions.paginationCurrentPage == 1) {
				loadData(q);
			} else {
				api.gridReset(null, $scope);
			}
		}

		$scope.add = function() {
			api.form({
				title: '新建规则',
				template: require('../views/form_rule.tpl.html'),
				name: 'meta_rule_add'
			}).then(function() {
				query();
			});
		}
		$scope.edit = function() {
			var id = api.getGridSelectedId($scope);
			api.form({
				title: '编辑规则',
				template: require('../views/form_rule.tpl.html'),
				name: 'meta_rule_edit',
				resolveWait: http.post({
					name: 'meta_rule',
					params: {
						id: id
					}
				})
			}).then(function() {
				query(false);
			});
		}
		$scope.remove = function() {
			var ids = api.getGridSelectedIds($scope);

			dialog.confirm('确定要删除选中项？').result.then(function(r) {
				if (r) {
					http.post({
						name: 'meta_rule_remove',
						params: {
							ids: ids
						},
						success: function() {
							query(false);
						}
					})
				}
			});
		}

		$scope.gridOptions = {
			paginationCurrentPage: api.page.pageNumber,
			paginationPageSize: api.page.pageSize,
			useExternalPagination: true,
			columns: [{
				name: '序号',
				width: 50,
				cellTemplate: '<div class="x-grid-inner">{{(grid.options.paginationCurrentPage - 1) * grid.options.paginationPageSize + (index + 1)}}</div>'
			}, {
				name: '规则名称',
				align: 'left',
				width: 150,
				field: 'ruleName'
			}, {
				name: '规则类型',
				width: 150,
				field: 'ruleType',
				cellTemplate: '<div class="x-grid-inner" ng-bind-html="grid.appScope.mapping(grid, row, col, \'types\')"></div>'
			}, {
				name: '备注',
				width: 300,
				field: 'ruleDesc',
				align: 'left'
			}],
			forceFit: false,
			onRegisterApi: function(api) {
				$scope.api = api;
				api.pagination && api.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
					query(false);
				});
			}
		};

		$scope.fields = {
			types: {
				'1': '指标检验',
				'2': '资源目录检验'
			}
		};

		$scope.mapping = function(grid, row, col, field) {
			return api.mapping({
				grid: grid,
				row: row,
				col: col,
				field: field,
				scope: $scope
			});
		}

		$scope.hasSelected = function() {
			return api.hasGridSelected($scope);
		}
		$scope.hasSelectedRecords = function() {
			return api.hasGridSelectedRecords($scope);
		}

		query();
	}
}